package com.example.dreamlist2.todo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.dreamlist2.CalendarUtils;
import com.example.dreamlist2.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;

public class TodoEditActivity extends AppCompatActivity {
    LinearLayout time_edit, date_edit, type_edit, edit_cancle, edit_commit, edit_delete;
    Switch switch_alert, switch_done;
    EditText etitle, econtent;
    TodoItem todoItem = new TodoItem();
    TextView show_date, show_time, show_type;
    String title, content, type, date1, time1;
    Integer done, Year, Month, Day, Hour, Minute;


    private AlertDialog alertDialog; //单选框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todo_edit);

        Intent intent = getIntent();
        todoItem = (TodoItem) intent.getSerializableExtra("item");
        if(todoItem == null){
            Log.i("edit","空参数");
        }
        BmobDate date = todoItem.getDate();
        date1 = date.getDate();
        time1 = date1.split(" ")[1];
        date1 = date1.split(" ")[0];

        Year = Integer.parseInt(date1.split("-")[0]);
        Month = Integer.parseInt(date1.split("-")[1]);
        Day = Integer.parseInt(date1.split("-")[2]);

        Hour = Integer.parseInt(time1.split(":")[0]);
        Minute= Integer.parseInt(time1.split(":")[1]);

        title = todoItem.getTitle();
        content = todoItem.getContent();
        type = todoItem.getType();

        time_edit = findViewById(R.id.time_edit);
        date_edit = findViewById(R.id.date_edit);
        type_edit = findViewById(R.id.type_edit);
        edit_cancle = findViewById(R.id.edit_cancle);
        edit_commit = findViewById(R.id.edit_commit);
        edit_delete = findViewById(R.id.edit_delete);
        switch_alert = findViewById(R.id.switch_alert_edit);
        switch_done = findViewById(R.id.switch_done_edit);
        show_date = findViewById(R.id.show_date_edit);
        show_time = findViewById(R.id.show_time_edit);
        show_type = findViewById(R.id.show_type_edit);
        etitle = findViewById(R.id.edit_todo_title_edit);
        econtent = findViewById(R.id.edit_todo_edit);

        etitle.setText(title);
        econtent.setText(content);
        show_date.setText(date1);
        show_time.setText(time1);
        show_type.setText(type);

//        Calendar mcalendar = Calendar.getInstance();     //  获取当前时间    —   年、月、日
//        Year = mcalendar.get(Calendar.YEAR);         //  得到当前年
//        Month = mcalendar.get(Calendar.MONTH);       //  得到当前月
//        Day = mcalendar.get(Calendar.DAY_OF_MONTH);  //  得到当前日
//        Hour  = mcalendar.get(Calendar.HOUR_OF_DAY);    //得到小时
//        Minute  = mcalendar.get(Calendar.MINUTE);            //得到分钟
        delete_alert();

        //todo:选择时间控件
        time_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int hour  = Hour;    //得到小时
                int min  = Minute;            //得到分钟
                new TimePickerDialog(TodoEditActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        // 得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                        Hour = hourOfDay;
                        Minute = minute;
                        show_time.setText(""+Hour+":"+Minute);
                    }
                }, hour, min, true).show();
            }
        });

        //todo:选择日期控件
        date_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int year = Year;         //  得到当前年
                int month = Month;       //  得到当前月
                int day = Day;  //  得到当前日

                new DatePickerDialog(TodoEditActivity.this, new DatePickerDialog.OnDateSetListener() { //  日期选择对话框
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        //得到选择后的 年，月，日，分别对应着三个参数 — year、month、dayOfMonth
                        Year = year;
                        Month = month;
                        Day = dayOfMonth;
                        show_date.setText(""+Year+"-"+Month+"-"+Day);
                        //Month = Month;
                    }
                },year,month,day).show();   //  弹出日历对话框时，默认显示 年，月，日
            }
        });

        //todo:选择类别控件
        type_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSingleAlertDialog(v);
            }
        });

        //取消并返回
        edit_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(2);
                TodoEditActivity.this.finish();
            }
        });

        //todo:上传数据库
        edit_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title = etitle.getText().toString();
                content = econtent.getText().toString();
                if(switch_done.isChecked()){
                    done = 1;
                }
                else{
                    done = 0;
                }
                if(switch_alert.isChecked() && done == 0){
                    edit_alert();
                }
                edit_todo();
            }
        });

        //todo:删除本条记录
        edit_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delete_todo();
            }
        });

    }

    //弹出类别选择框
    private void showSingleAlertDialog(View view) {
        final String[] items = {"未定义", "工作", "学习", "生活", "社交", "其他"};
        int checked = 0, i;
        for(i = 0; i<6; i++){
            if(items[i].equals(type)){
                checked = i;
            }
        }
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(TodoEditActivity.this);
        alertBuilder.setTitle("选择类别");
        alertBuilder.setSingleChoiceItems(items, checked, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                type = items[i];
                Toast.makeText(TodoEditActivity.this, items[i], Toast.LENGTH_SHORT).show();
            }
        });

        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                show_type.setText(type);
                alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog.dismiss();
            }
        });
        alertDialog = alertBuilder.create();
        alertDialog.show();
    }

    private void edit_todo(){
        todoItem.setTitle(title);
        todoItem.setContent(content);
        todoItem.setF_done(done);
        todoItem.setType(type);
        Date d = new Date();
        Month = Month + 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start_time = Year.toString()+"-"+Month.toString()+"-"+Day.toString()+" "
                +Hour.toString()+":"+Minute.toString()+":00";
        try {
            d = sdf.parse(start_time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        BmobDate bdate = new BmobDate(d);
        todoItem.setDate(bdate);

        todoItem.update(todoItem.getObjectId(), new UpdateListener() {

            @Override
            public void done(BmobException e) {
                if(e==null){
                    Log.i("bmob","更新成功");
                    Toast.makeText(TodoEditActivity.this, "修改成功！", Toast.LENGTH_SHORT);
                    setResult(2);
                    finish();
                }else{
                    Log.i("bmob","更新失败："+e.getMessage()+","+e.getErrorCode());
                    Toast.makeText(TodoEditActivity.this, "修改失败……", Toast.LENGTH_SHORT);
                }
            }

        });
    }

    private void edit_alert(){
        long begin_time = CalendarUtils.remindTimeCalculator(Year,Month, Day, Hour, Minute);
        long end_time = CalendarUtils.remindTimeCalculator(Year, Month, Day+1, Hour, Minute);
        CalendarUtils.onCalendarRemindListener callback = null;
        CalendarUtils.addCalendarEventRemind(TodoEditActivity.this, title, content, begin_time, end_time, 0, callback);
    }

    private void delete_alert(){
        long begin_time = CalendarUtils.remindTimeCalculator(Year,Month, Day, Hour, Minute);
        CalendarUtils.onCalendarRemindListener callback = null;
        CalendarUtils.deleteCalendarEventRemind(TodoEditActivity.this, title, content, begin_time, callback);
    }

    private void delete_todo(){
        todoItem.delete(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    Log.i("bmob","删除todo成功");
                    Toast.makeText(TodoEditActivity.this, "删除成功！", Toast.LENGTH_SHORT);
                    setResult(2);
                    finish();
                }else{
                    Toast.makeText(TodoEditActivity.this, "删除失败……", Toast.LENGTH_SHORT);
                    Log.i("bmob","删除todo失败："+e.getMessage()+","+e.getErrorCode());
                }
            }
        });
    }
}